package com.itheima.travel.service.impl;

import com.itheima.travel.dao.UserDao;
import com.itheima.travel.domain.ResultInfo;
import com.itheima.travel.domain.User;
import com.itheima.travel.service.UserService;
import com.itheima.travel.utils.Md5Utils;
import com.itheima.travel.utils.SmsUtils;
import com.itheima.travel.utils.UuidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Transactional
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Override
    public ResultInfo register(User user) {
        User dbUser = userDao.findByUserName(user.getUsername());
        if (dbUser !=null){
            return new ResultInfo(false,"用户名已经存在");
        }
        dbUser = userDao.findByTelephone(user.getTelephone());

        if (dbUser !=null){
            return new ResultInfo(false,"手机号已经存在");
        }
        String uuid = UuidUtils.simpleUuid();
        String md5 = Md5Utils.getMd5(user.getPassword() + uuid);
        user.setSalt(uuid);
        user.setPassword(md5);
        userDao.save(user);
        ResultInfo resultInfo = new ResultInfo(true, "注册成功");
        return resultInfo;
    }

    @Override
    public ResultInfo sendSms(String telephone, String authCode) {
//        String code = SmsUtils.send(telephone, "黑马旅游网", "SMS_198917972", authCode);
        String code="ok";
        if ("ok".equalsIgnoreCase(code)){
            redisTemplate.opsForValue().set("smsCode",authCode);
            return  new ResultInfo(true,"发送成功");
        }else {
            return new ResultInfo(false,"发送失败");
        }

    }

    @Override
    public User findByUserName(String username) {
        User user = userDao.findByUserName(username);
        return user;
    }
@Autowired
  private   RedisTemplate redisTemplate;
    @Override
    public ResultInfo login(Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password");
        String smsCode = map.get("smsCode");
        User dbUser = userDao.findByUserName(username);
        if (dbUser==null){
            return new ResultInfo(false,"用户名或密码错误");
        }
        String newMd5 = Md5Utils.getMd5(password + dbUser.getSalt());
        String dbMd5 = Md5Utils.getMd5(dbUser.getPassword() + dbUser.getSalt());
        if (!dbMd5.equals(newMd5)){
            return new ResultInfo(false,"用户名和或密码错误");
        }
        String redisCode = (String) redisTemplate.opsForValue().get("smsCode" + dbUser.getTelephone());

        if (!smsCode.equalsIgnoreCase(redisCode)){
            return new ResultInfo(false,"验证码错误");
        }
        return new ResultInfo(true,"登陆成功",dbUser);
    }
}
